//
//  MapAddressViewController.m
//  QT
//
//  Created by 甘世清 on 2025/1/6.
//

#import "MapAddressViewController.h"

@interface MapAddressViewController ()<MKMapViewDelegate,UITextFieldDelegate>
@property (nonatomic , strong) MKMapView * mapView;
@property (nonatomic , strong) UILabel * addressLabel;
@property (nonatomic , strong) NSMutableDictionary * data;
@end

@implementation MapAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[SQCLLocationManager sharedManager] SQ_startUpdatingLocation];
    WS(weakSelf);
    [self zx_setRightBtnWithText:SQNSLocalString(@"确定") clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
        [weakSelf SQ_addressStringForMap];
    }];
}

- (void)SQ_UIViewForSelfView{
    [self.view addSubview:self.mapView];
    UIImageView * image = [[UIImageView alloc]init];
    image.image = SQGetImage(@"dingwei");
    image.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:image];
    [image mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view.mas_centerY).offset(-10);
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(40);
    }];
    [self.view addSubview:self.addressLabel];
    [self.addressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.bottom.equalTo(image.mas_top).offset(-2);
            make.width.mas_equalTo(SCREEN_WIDETH/3.f);
    }];
    [self SQ_setMap];
}

-(void)SQ_setMap{
    CLLocationCoordinate2D coordinate2D = CLLocationCoordinate2DMake([UserModel share].lat, [UserModel share].lng);
       // 设置地图显示区域的缩放级别
    MKCoordinateSpan span = MKCoordinateSpanMake(0.004, 0.004);
       // 初始化一个常量，表示地图对象的显示区域
       MKCoordinateRegion region = MKCoordinateRegionMake(coordinate2D,span);
       // 设置地图对象的显示区域
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
}


//位置已经改变了
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    CLLocationCoordinate2D  location =  [self.mapView convertPoint:CGPointMake(SCREEN_WIDETH/2.f, SCREEN_HEIGHT/2.f) toCoordinateFromView:self.mapView];
         CLGeocoder *gecoder = [[CLGeocoder alloc]init];
         CLLocation *locations = [[CLLocation alloc]initWithLatitude:location.latitude longitude:location.longitude];
    self.data = [[NSMutableDictionary alloc]init];
    [self.data setObject:[NSString stringWithFormat:@"%.6f",location.latitude] forKey:@"lat"];
    [self.data setObject:[NSString stringWithFormat:@"%.6f",location.longitude] forKey:@"lng"];
    WS(weakSelf);
        [gecoder reverseGeocodeLocation:locations completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            
            if (placemarks.count > 0) {
                CLPlacemark * place = placemarks.firstObject;
               
                if ([place.thoroughfare isNotEmpty]) {
                    weakSelf.addressLabel.text = [NSString stringWithFormat:@"%@%@",place.subLocality,place.thoroughfare];
                } else {
                    weakSelf.addressLabel.text = [NSString stringWithFormat:@"%@%@",place.subLocality,place.name];
                }
                weakSelf.addressLabel.text = [weakSelf.addressLabel.text stringByReplacingOccurrencesOfString:@"null" withString:@""];
                weakSelf.addressLabel.text = [weakSelf.addressLabel.text stringByReplacingOccurrencesOfString:@"()" withString:@""];
                weakSelf.addressLabel.text = [weakSelf.addressLabel.text stringByReplacingOccurrencesOfString:@"nil" withString:@""];
            }
        }];
}

-(void)SQ_addressStringForMap{
    if (![self.addressLabel.text isNotEmpty]) {
        [self SQ_headerButtonClick];
        return;
    }
    [self.data setObject:self.addressLabel.text forKey:@"address"];
    if (self.addressButtonBlock) {
        self.addressButtonBlock(self.data);
    }
    [self SQ_popViewVC];
}


-(void)SQ_headerButtonClick{
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:SQNSLocalString(@"定位权限设置") message:@"未检测到授权定位权限,请前往设置进行授权" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * co0 = [UIAlertAction actionWithTitle:SQNSLocalString(@"去授权") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];

            if ([[UIApplication sharedApplication] canOpenURL:url]) {
               [[UIApplication sharedApplication] openURL:url];
            }
    }];
 
    UIAlertAction * co2 = [UIAlertAction actionWithTitle:SQNSLocalString(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:co0];
    [alert addAction:co2];
    [self presentViewController:alert animated:YES completion:nil];
}

/** 懒加载地图视图 */
- (MKMapView *)mapView{
    if (!_mapView) {
        _mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT)];
        /** 设置地图类型 */
        _mapView.mapType = MKMapTypeMutedStandard;
        _mapView.userTrackingMode = MKUserTrackingModeFollow;
        //设置地图可缩放
        _mapView.zoomEnabled = YES;
        //设置地图可滚动
        _mapView.scrollEnabled = YES;
        //设置地图可旋转
        _mapView.rotateEnabled = YES;
        //设置显示用户显示位置
        _mapView.showsUserLocation = YES;
        //为MKMapView设置delegate
        _mapView.delegate = self;
        _mapView.showsBuildings = YES;
        _mapView.showsTraffic = YES;
    }
    return _mapView;
}

- (UILabel *)addressLabel{
    if (!_addressLabel) {
        _addressLabel = [[UILabel alloc]init];
        _addressLabel.font = FONT_REGULAR(12);
        _addressLabel.textColor = UIColor.blackColor;
        _addressLabel.numberOfLines = 0;
        _addressLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _addressLabel;
}


@end
